package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.user.dto.ApAuthor;
import com.heima.user.dto.AuthDto;
import com.heima.user.dto.WmUser;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserRealname;
import com.heima.user.feign.ArticleClient;
import com.heima.user.feign.MediaClient;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.IApUserRealnameService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.user.service.IApUserService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-11-07
 */
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements IApUserRealnameService {

    @Override
    public ResponseResult listByStatus(AuthDto dto) {
        // 分页查询实名认证信息
        IPage<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> query = new LambdaQueryWrapper<>();
        // 判断status不为空,添加状态查询
        if (dto.getStatus() != null) {
            query.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        IPage<ApUserRealname> iPage = this.page(page, query);
        // 构建通用分页响应
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), iPage.getTotal(), iPage.getRecords());
        return result;
    }

    @Autowired
    private IApUserService userService;

    /**
     * 审核
     *
     * @param dto
     * @param type 1:通过  0:不通过
     * @return
     */
    @Override
    // @Transactional
    @GlobalTransactional
    public ResponseResult auth(AuthDto dto, int type) {
        // 根据认证表id查询认证信息
        ApUserRealname apUserRealname = this.getById(dto.getId());
        // 如果是审核不通过,修改认证状态为 2 ,并且记录失败原因
        if (type == 0) {
            apUserRealname.setStatus(2);
            apUserRealname.setReason(dto.getReason());
            this.updateById(apUserRealname);
            return ResponseResult.okResult();
        }
        // 如果是审核通过
        // 查询用户注册表信息
        ApUser apUser = userService.getById(apUserRealname.getUserId());
        // 根据用户注册信息表去自动注册自媒体账号
        WmUser wmUser = createWmUser(apUser);
        // 创建文章作者
        if (wmUser != null) {
            ApAuthor author = createAuthor(wmUser, apUser);
            if (author != null) {
                // 模拟异常
                // int i = 1 / 0;
                // 将作者的id更新到自媒体账号表中
                wmUser.setApAuthorId(author.getId());
                mediaClient.updateWmUser(wmUser);
                // 修改认证状态为 9
                apUserRealname.setStatus(9);
                this.updateById(apUserRealname);
                // 修改注册表中标识flag为 1 自媒体人
                apUser.setFlag(1);
                userService.updateById(apUser);
            }
        }
        return ResponseResult.okResult();
    }

    @Autowired
    private ArticleClient articleClient;

    /**
     * 创建文章作者
     *
     * @param wmUser
     * @param apUser
     * @return
     */
    private ApAuthor createAuthor(WmUser wmUser, ApUser apUser) {
        ApAuthor apAuthor = new ApAuthor();
        apAuthor.setName(apUser.getName());
        apAuthor.setType(2);
        apAuthor.setUserId(apUser.getId());
        apAuthor.setWmUserId(wmUser.getId());
        ResponseResult<ApAuthor> responseResult = articleClient.saveApAuthor(apAuthor);
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApAuthor data = responseResult.getData();
            return data;
        } else {
            throw new RuntimeException("调用文章服务异常...");
        }
        // return null;
    }

    @Autowired
    private MediaClient mediaClient;

    /**
     * 创建自媒体账号
     *
     * @param apUser
     * @return
     */
    private WmUser createWmUser(ApUser apUser) {
        // 构建自媒体账号
        WmUser wmUser = new WmUser();
        // 拷贝基本属性
        BeanUtils.copyProperties(apUser, wmUser);
        wmUser.setId(null);
        wmUser.setApUserId(apUser.getId());
        wmUser.setNickname(apUser.getName());
        wmUser.setStatus(9);
        wmUser.setType(0);
        // 远程调用自媒体服务接口
        ResponseResult<WmUser> responseResult = mediaClient.saveWmUser(wmUser);
        // 调用成功
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            WmUser data = responseResult.getData();
            return data;
        }
        return null;
    }
}
